package com.minglan.leetcode.java.solution2103;

/*
 * 2021.3.10 
 * 224. 基本计算器
 * 实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。

示例 1：
输入：s = "1 + 1"
输出：2

示例 2：
输入：s = " 2-1 + 2 "
输出：3

示例 3：
输入：s = "(1+(4+5+2)-3)+(6+8)"
输出：23

 */
public class Calculate {
	
    public int calculate(String s) {
    	s=s.replace(" ", "");
    	int ret=0;
    	int indexStart=0;
    	int indexEnd=0;
    	char lastoper='+';
    	for(int i=0;i<s.length();i++) {
    		char c = s.charAt(i);
    		if(c=='(') {
    			int subend=chk(s,i+1);
    			System.out.println(" call subfunction ["+s.substring(i+1,subend)+"]");
    			ret=comput(ret,calculate(s.substring(i+1,subend)),lastoper);
    			System.out.println("after call subfunc ret="+ret);
    			i=subend;
    			indexStart=subend+1;
    			continue;
    		}
    		if(c == '+' || c=='-' ) {
    			indexEnd=s.indexOf(c, indexStart) ;
    			if(indexEnd==indexStart) {
        			indexStart = indexEnd+1;
        			lastoper=c;
        			continue;
    			}
    			System.out.println(s+" -> " + indexStart + ","+indexEnd+"  =>" + s.substring(indexStart, indexEnd));
    			int curInt = Integer.parseInt(s.substring(indexStart, indexEnd));
    			ret=comput(ret,curInt,lastoper);
    			indexStart = indexEnd+1;
    			lastoper=c;
    			System.out.println("ret="+ret+ "  indexStart="+indexStart);
    		}
    	}

		System.out.println(s+" -> " + indexStart + ","+s.length()+"  =>" + s.substring(indexStart, s.length()));
		if(indexStart < s.length()) {
			int curInt = Integer.parseInt(s.substring(indexStart, s.length()));
			ret=comput(ret,curInt,lastoper);
		}
		System.out.println("ret="+ret);

		return ret;
    }
    
    int comput(int a,int b,char oper) {
    	System.out.println("function comput "+a+ " " + oper + " " + b);
    	if(oper=='+') return a+b;
    	if(oper=='-') return a-b;
    	return 0;
    }
    
    int chk(String s,int start) {
    	int end=0;
    	int cnt=1;
    	for(int i=start;i<s.length();i++) {
    		char c = s.charAt(i);
    		if( c == '(' ) cnt ++;
    		if( c== ')') cnt--;
    		if( cnt == 0 ) { end=i;break; }
    	}
    	return end;	
    }
    
	public static void main(String[] args) {
		Calculate c = new Calculate();
		System.out.println(c.calculate("(1+(4+5+2)-3)+(6+8)"));
		

	}

}
